package by.grsu.shakh.page.librarian;

import java.util.Arrays;
import java.util.List;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.CompoundPropertyModel;

import by.grsu.shakh.app.LibraryWebApplication;
import by.grsu.shakh.dao.UserDao;
import by.grsu.shakh.entity.User;
import by.grsu.shakh.entity.UserRole;
import by.grsu.shakh.validator.GMailAddressValidator;

/**
 * "edit" page for User object.
 * 
 * @author shakh_andrew
 */
public class UserEditPage extends WebPage {

	public UserEditPage(final User user) {
		super();

		final Form<User> form = new Form<User>("form",
				new CompoundPropertyModel<User>(user));
		add(form);

		form.add(new TextField<String>("login"));
		form.add(new TextField<String>("password"));
		form.add(new TextField<String>("firstName"));
		form.add(new TextField<String>("surName"));
		form.add(new TextField<String>("adress"));
		form.add(new TextField<String>("mail").add(new GMailAddressValidator()));
		final List role = Arrays.asList(UserRole.librarian, UserRole.reader);
		ListChoice listChoice = new ListChoice("role", role);
		listChoice.setMaxRows(2);
		form.add(listChoice);

		form.add(new SubmitLink("save") {
			@Override
			public void onSubmit() {
				super.onSubmit();
				final UserDao userDao = new UserDao(
						LibraryWebApplication.DATA_XML_FOLDER);
				if (user.getId() == null) {
					userDao.saveNew(user);
				} else {
					userDao.update(user);
				}
				setResponsePage(new ListUserPage());
			}
		});

		form.add(new Link("cancel") {
			@Override
			public void onClick() {
				setResponsePage(new ListUserPage());
			}
		});
	}
}
